import 'dart:convert';
import 'dart:developer';

import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/LoadToast.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/SetPower.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/ShowToast.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/requestUrl.dart';
import 'package:shared_preferences/shared_preferences.dart';

/**
 * Creat For 11643
 * CreatTime 2022/12/2
 * Description:
 */
class Search extends StatefulWidget {
  const Search({Key? key}) : super(key: key);

  @override
  _SearchState createState() => _SearchState();
}

class _SearchState extends State<Search> {
  //原生主动向flutter发送数据通道
  static const channel = const BasicMessageChannel(
      'com.flutter.BasicMessageChannel', StandardMessageCodec());
  ///定义一个通道,flutter调用原生方法
  static const platform = const MethodChannel('com.RfidRead.rfidread');
  ///垛信息列表
  var GoodsList = [];
  ///EPC和条码编码放一起的数组
  var EpcAndBarCode = [];
  //是否正在读取中
  var IsReading = false;

  //手持机是否初始化成功
  var IsInit = "false";

  //扫描器打卡状态
  var IsOpen = "false";
  ///分组入库信息列表
  List<DataRow> KuMessage = [];
String ApiUrl = "";
  String Token = "";
  ///页面加载
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration.zero,() async {
      final SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();
      // 获取本地ip地址
      ApiUrl =(await sharedPreferences.getString('ApiUrl'))!;
      Token = sharedPreferences.getString('Token')!;
      InitRfid();
    });
  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if(IsInit=="true"){
      DisScan();
      DisposeRFID();
    }
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            "查看",
            style: TextStyle(fontSize: 15),
          ),
          actions: [
            IconButton(
                onPressed: () {
                  if(IsReading){
                    ShowToast().MyToast("请先停止读卡");
                    return;
                  }
                  //  点击进去设置功率页面
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => SetPower(
                            SetPowerType: "SearchPower",
                          )));
                },
                icon: Icon(Icons.settings)),
          ],
        ),
        body: Column(
          children: [
            Expanded(
              child: Container(
                // padding: EdgeInsets.only(left: 15,right: 15),
                child: Column(
                  children: [
                    Container(
                      padding: EdgeInsets.only(left: 15, right: 15, top: 15),
                      alignment: Alignment.topLeft,
                      child: Text(
                        "标签数量：${GoodsList.length}",
                        style: TextStyle(
                            fontSize: 17, fontWeight: FontWeight.w600),
                      ),
                    ),
                    Container(
                      child: Expanded(
                        child: ListView.separated(
                          itemCount: GoodsList.length,
                          itemBuilder: (context, index) {
                            return GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              child: Container(
                                padding: EdgeInsets.only(left: 15,right: 15),
                                alignment: Alignment.topLeft,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Container(
                                      child:  Text("RFID编号:${GoodsList[index]['RFIDCode']}"),
                                    ),
                                    Container(
                                      child:  Text("资产类别:${GoodsList[index]['Name']}"),
                                    ),
                                    Row(
                                      children: [
                                        Container(
                                          child:  Text("存放地点:${GoodsList[index]['WarehouseIDName']}"),
                                        ),
                                        Container(
                                          child:  Text("资产状态:${GoodsList[index]['ExistState']==0?"在库":GoodsList[index]['ExistState']==1?"出库":"借用"}"),
                                        ),
                                      ],
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    ),
                                    Row(
                                      children: [
                                        Container(
                                          child:  Text("维保状态:${GoodsList[index]['FactoryState']==0?"正常":"维保中"}"),
                                        ),
                                        Container(
                                          child:  Text("使用状态:${GoodsList[index]['UseState']==0?"未使用":"使用中"}"),
                                        ),
                                      ],
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    ),
                                  ],
                                ),
                              ),
                            );
                          }, separatorBuilder: (BuildContext context, int index) {
                          return Divider();
                        },),
                      ),
                    )
                    // Spacer(),
                  ],
                ),
              ),
            ),

            ///底部按钮
            Container(
              height: 50,
              width: MediaQuery.of(context).size.width - 30,
              child: GridView(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                ),
                children: [
                  GestureDetector(
                    child: Container(
                      alignment: Alignment.topCenter,
                      child:   Column(
                        children: [
                          Icon( Icons.wifi,color:IsReading?Colors.red:Colors.black38),
                          Text(IsReading?"停止读取":"开始读取",style: TextStyle(fontSize: 13,color: IsReading?Colors.red:Colors.black38))
                        ],
                      ),
                    ),
                    onTap: (){
                      if(IsReading){
                        //停止读卡
                        StopRead();
                      }else{
                        //读卡
                        ReadRfid();
                      }

                    },
                  ),
                  GestureDetector(
                    onTap: (){
                      if(IsReading){
                        ShowToast().MyToast("请先停止读卡");
                        return;
                      }
                      showAlertDialogClear();
                    },
                    child: Container(
                      alignment: Alignment.topCenter,
                      child:   Column(
                        children: [
                          Icon(Icons.delete,color: Colors.orange),
                          Text("清空数据",style: TextStyle(fontSize: 13,color: Colors.orange))
                        ],
                      ),
                    ),
                  )

                ],
              ),
            ),
            Container(
              height: 10,
            )
          ],
        )// This trailing comma makes auto-formatting nicer for build methods.
    );
  }
  //  初始化rfid
  Future<void> InitRfid() async {
    // 加载框
    LoadToast().LoadingToast("初始化中...", context);
    var isinit = await platform.invokeMethod("InitRfid");
    //取出本地保存的功率
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    IsInit = isinit;
    if (isinit == "true") {
      print("初始化成功");
      if (await sharedPreferences.getInt("SearchPower") != null) {
        var Power = await sharedPreferences.getInt("SearchPower");
        //  设置功率
        bool IsSet = await platform.invokeMethod('SetPower', Power);
        if (IsSet) {
          new ShowToast().MyToast("初始化成功");
        }
      } else {
        //  用系统给用户默认的功率10
        //  设置功率
        bool IsSet = await platform.invokeMethod('SetPower', 20);
        if (IsSet) {
          new ShowToast().MyToast("初始化成功");
          //  保存本地
          await sharedPreferences.setInt("SearchPower", 20);
        }
      }
    } else {
      ShowToast().MyToast("初始化失败，请重新进入此页面!");
    }
    // GetLocationList();
    IniListenNative();
    OpenScan();
    print("初始化设备结果$isinit");
  }

  // 读取
  ReadRfid() async {
    IsReading = true;
    setState(() {
    });
    platform.invokeMethod('ReadRfid');
  }

  ReadRfidOne() {
    platform.invokeMethod('ReadRFIDOne');
  }

  // 停止读卡
  StopRead() async {
    IsReading = false;
    setState(() {
    });
    platform.invokeMethod('StopReadRfid');
  }

  // 销毁rfid
  DisposeRFID() {
    IsInit = "false";
    platform.invokeMethod('onDestroy');
  }
  //打开扫描
  OpenScan() async {
    platform.invokeMethod('InitScan');
  }
  //开始扫描
  StartScan() {
    platform.invokeMethod('StartScan');
  }

  //销毁扫描
  DisScan() {
    platform.invokeMethod('DestoryScan');
  }
  //  注册监听原生发送的数据
  IniListenNative() {
    LoadToast().CloseLoading();
    var value;
    channel.setMessageHandler((message) async {
      print("BluDemo已接受到原生主动发出的数据$message");
      value = json.decode(message.toString());
      if (value['Type'] == "Scan") {
        // value['ScanData']
        if(value['ScanData']!=""&&value['ScanData']!=null){
          ///判断是否读取重复
          if(!EpcAndBarCode.contains(value['ScanData'])){
            EpcAndBarCode.add(value['ScanData']);
            ///请求原生网络请求
            var data = {
              "ID":value['ScanData'],
              "Url":ApiUrl+"/api/AppAssetStock/GetModel",
              "Token":Token
            };
            platform.invokeMethod('GetRfidMessagePost',data);
          }
        }
      } else if (value['Type'] == "onKeyDown") {
        //  监听摁键摁下
        ReadRfid();
      } else if (value['Type'] == "onKeyUp") {
        //摁键抬起
        StopRead();
      } else if(value['Type'] == "Request"){
        if(value['Data']!=""&&value['Data']!=null){
          GoodsList.add(value['Data']);
          setState(() {
          });
        }

      }
      else {
        if (value['Epc'] != "") {
          print("RFID编码${value['Epc']}");
          ///判断是否读取重复
          if(!EpcAndBarCode.contains(value['Epc'])){
            EpcAndBarCode.add(value['Epc']);
            // GetTagMessage(value['Epc']);
            ///请求原生网络请求
            var data = {
              "ID":value['Epc'],
              "Url":ApiUrl+"/api/AppAssetStock/GetModel",
              "Token":"Token=$Token"
            };
            platform.invokeMethod('GetRfidMessagePost',data);

          }
        }
      }

    });
  }

  Clear(){
    GoodsList.clear();
    EpcAndBarCode.clear();
    ShowToast().MyToast("清空成功!");
    setState(() {
    });
  }
  ///弹窗
  void showAlertDialogClear() {
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: new Text('警告！'),
            //可滑动
            content: Text("确定要清空数据吗？"),
            actions: <Widget>[
              new FlatButton(
                child: new Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop();
                  Clear();
                },
              ),
              new FlatButton(
                child: new Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        });
  }
}